<template>
  <div class="consumer-page activity-list-page">
    <el-breadcrumb class="breadcrumb page-title" separator="/">
      <el-breadcrumb-item :to="{ path: '/propertyIndex'}">Property</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/propertyEdit'}">Edit</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="container-padding">
      <!--serchBox-->
      <div class="search-box">
        <el-form :inline="true" label-position="top" :model="form" size="mini" ref="form" :rules="rules"
                 class="demo-ruleForm main-search-box">
          <el-row>
            <!--Status-->
            <el-form-item label="Status" style="margin-right: 10px">
              <el-select style="width: 140px" v-model="form.status" placeholder="">
                <el-option v-for="i in statusOption" :key="i.value" :label="i.label" :value="i.value"></el-option>
              </el-select>
            </el-form-item>
            <!--name-->
            <el-form-item label="Name" style="width: 250px;">
              <el-input v-model="form.name" placeholder=""></el-input>
            </el-form-item>
            <el-form-item label="Mm Name" style="width: 250px;">
              <el-input v-model="form.nameMm" placeholder=""></el-input>
            </el-form-item>
            <!--search-->
            <el-form-item style="margin-top: 37px">
              <el-button @click="$router.back(-1)" type="info" style="width:80px;margin-left: 30px;">Cancel</el-button>
            </el-form-item>
            <el-form-item style="margin-top: 37px;">
              <el-button @click="editProperty" type="success" style="width:80px">Save</el-button>
            </el-form-item>
          </el-row>

          <!--<el-row>-->
            <!--&lt;!&ndash; 级联菜单 &ndash;&gt;-->
            <!--&lt;!&ndash;第一级菜单&ndash;&gt;-->
            <!--<el-form-item label="Category1" style="width: 200px;margin-right: 10px" prop="firstCategory">-->
              <!--<el-select style="width: 200px" v-model="form.firstCategory" @change="getSecondaryData">-->
                <!--<el-option v-for="i in categoryData" :key="i.id" :label="i.name" :value="i.name"></el-option>-->
              <!--</el-select>-->
            <!--</el-form-item>-->
            <!--&lt;!&ndash;第二级菜单&ndash;&gt;-->
            <!--<el-form-item label="Category2" style="width: 200px;margin-right: 10px"-->
                          <!--v-if="secondaryData.length>0||form.secondaryCategory" prop="secondaryCategory">-->
              <!--<el-select style="width: 200px" v-model="form.secondaryCategory" @change="getThirdData"-->
              <!--&gt;-->
                <!--<el-option v-for="i in secondaryData" :key="i.id" :label="i.name" :value="i.name"></el-option>-->
              <!--</el-select>-->
            <!--</el-form-item>-->
            <!--&lt;!&ndash;第三级菜单&ndash;&gt;-->
            <!--<el-form-item label="Category3" style="width: 200px;margin-right: 10px"-->
                          <!--v-if="thirdData.length>0||form.thirdCategory"-->
                          <!--prop="thirdCategory">-->
              <!--<el-select style="width: 200px" v-model="form.thirdCategory" @change="getNewId">-->
                <!--<el-option v-for="i in thirdData" :key="i.id" :label="i.name" :value="i.name"></el-option>-->
              <!--</el-select>-->
            <!--</el-form-item>-->
            <!--<el-form-item style="margin-top: 37px;">-->
              <!--<el-button @click="addCategory" type="success" style="width:80px">Add</el-button>-->
            <!--</el-form-item>-->
          <!--</el-row>-->


        </el-form>
      </div>

      <!--categoryList-->
      <!--<div style="margin:10px 0;">-->
        <!--<el-row :gutter="12">-->
          <!--<el-col :span="12" v-for="(item,index) in categoryList">-->
            <!--<div class="card-wraper">-->
              <!--<el-card shadow="hover">-->
                <!--{{item.categoryName}}-->
              <!--</el-card>-->
              <!--<i class="el-icon-delete delete-icon" @click="deleteItem(index)"></i>-->
            <!--</div>-->
          <!--</el-col>-->
        <!--</el-row>-->
      <!--</div>-->
      <!--list-->
      <div class="list-items-box">
        <el-table
          :data="tableData"
          v-loading="tableLoading"
          border
          ref="singleTable"
          highlight-current-row
          @current-change="handleCurrentChange"
          style="width: 100%"
          :row-class-name="tableRowClassName"
        >
          <!--ID-->
          <el-table-column
            prop="id"
            label="ID"
            align="center"
            width="80">
          </el-table-column>
          <!--edit-->
          <el-table-column
            prop="" label="English"
            align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="propertyValueEdit(scope,1)">
                {{unicodeTozawgyi(scope.row.value)}}
              </el-button>
            </template>
          </el-table-column>
          <!--mm-->
          <el-table-column
            prop="" label="Mm"
            align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="propertyValueEdit(scope,2)">
                {{unicodeTozawgyi(scope.row.valueMm)}}
              </el-button>
            </template>
          </el-table-column>
          <!--delete-->
          <!--<el-table-column-->
            <!--prop="" label="Delete"-->
            <!--align="center">-->
            <!--<template slot-scope="scope">-->
              <!--<el-button type="text" size="small" @click="deletePropertyValue(scope)">Delete</el-button>-->
            <!--</template>-->
          <!--</el-table-column>-->
        </el-table>
        <!--分页-->
        <div class="block" style="margin-top: 15px;text-align: center;">
          <el-pagination
            @size-change="handleChangeSize"
            @current-change="handleChangePage"
            :current-page="pageData.pageNum"
            :page-size="pageData.pageSize"
            :page-sizes="[10, 20, 50, 100, 500]"
            :page-count="pageInfo.totalPages"
            :total="pageInfo.totalCount"
            layout="total, prev, pager, next, jumper, sizes">
          </el-pagination>
        </div>
      </div>

      <!--新增属性值-->
      <!--<el-form :inline="true" label-position="top" :model="addForm" size="mini" ref="ruleForm"-->
               <!--class="demo-ruleForm main-search-box">-->
        <!--<el-row>-->
          <!--&lt;!&ndash;name&ndash;&gt;-->
          <!--<el-form-item label="Name" style="width: 250px;">-->
            <!--<el-input v-model="addForm.value" placeholder=""></el-input>-->
          <!--</el-form-item>-->
          <!--<el-form-item label="Mm Name" style="width: 250px;">-->
            <!--<el-input v-model="addForm.valueMm" placeholder=""></el-input>-->
          <!--</el-form-item>-->
          <!--<el-form-item style="margin-top: 37px;">-->
            <!--<el-button @click="addPropertyValue" type="success" style="width:80px">Save</el-button>-->
          <!--</el-form-item>-->
        <!--</el-row>-->
      <!--</el-form>-->
    </div>

  </div>
</template>

<script>

  import {
    getPropertyDetail,
    getSubProperty,
    updateProperty,
    propertyValueEdit,
    propertyValueAdd,
    getCategory
  } from '../../api/guc_api.js'
  import Qs from "qs";

  export default {
    name: 'propertyEdit',
    data() {
      return {
        categoryData: [],
        secondaryData: [],
        thirdData: [],
        categoryId: '',
        categoryName: '',
        id: '',
        categoryList: [],
        form: {
          status: '',
          name: '',
          nameMm: '',
          firstCategory: '',
          secondaryCategory: '',
          thirdCategory: '',
        },
        addForm: {
          propertyId: '',
          value: '',
          valueMm: '',
        },
        statusOption: [
          {
            label: 'Active',
            value: '1'
          },
          {
            label: 'Deleted',
            value: '0'
          }
        ],
        pageData: {
          pageNum: 1,
          pageSize: 10,
        },
        pageInfo: {
          totalCount: 0,
          totalPages: 0
        },
        tableLoading: false,
        tableData: [],
        // 当前行
        currentRow: null,
        //校验
        rules: {
          firstCategory: [
            {required: true, message: 'please select category1', trigger: 'change'}
          ],
          secondaryCategory: [
            {required: true, message: 'please select category2', trigger: 'change'}
          ],
          thirdCategory: [
            {required: true, message: 'please select category3', trigger: 'change'}
          ]
        },
      }
    },
    methods: {
      //下面是对category菜单的操作。。。。。。。。。。。。。。。。。。。。。。。。。
      // // 获取二级菜单
      // getSecondaryData() {
      //   this.form.secondaryCategory = ''
      //   this.secondaryData = []
      //   this.form.thirdCategory = ''
      //   this.thirdData = []
      //   let index
      //   index = this.categoryData.findIndex((item) => {
      //     return item.name === this.form.firstCategory
      //   })
      //   this.secondaryData = this.categoryData[index].children
      //   if (this.form.firstCategory) {
      //     this.categoryData.forEach((item) => {
      //       if (item.name === this.form.firstCategory) {
      //         this.categoryId = item.id
      //         this.categoryName = item.name
      //       }
      //     })
      //   }
      // },
      // // 获取三级菜单
      // getThirdData() {
      //   this.form.thirdCategory = ''
      //   this.thirdData = []
      //   let index
      //   index = this.secondaryData.findIndex((item) => {
      //     return item.name === this.form.secondaryCategory
      //   })
      //   this.thirdData = this.secondaryData[index].children
      //   if (this.form.secondaryCategory) {
      //     this.secondaryData.forEach((item) => {
      //       if (item.name === this.form.secondaryCategory) {
      //         this.categoryId = item.id
      //         this.categoryName += '/' + item.name
      //       }
      //     })
      //   }
      // },
      // //获取新的catId
      // getNewId() {
      //   if (this.form.thirdCategory) {
      //     this.thirdData.forEach((item) => {
      //       if (item.name === this.form.thirdCategory) {
      //         this.categoryId = item.id
      //         this.categoryName += '/' + item.name
      //       }
      //     })
      //   }
      // },
      // //增加category
      // addCategory() {
      //   // 然后验证表单信息
      //   this.$refs['form'].validate((valid) => {
      //     if (!valid) {
      //       this.messageToastErr('Wrong Submit')
      //       return false
      //     }
      //     else {
      //       let newCategory = {
      //         id: this.categoryId,
      //         categoryName: this.categoryName
      //       }
      //       //要校验一下这个分类是否已经存在了，如果已经存在就不能再添加了，并弹出提示
      //       let ifAdd = true
      //       this.categoryList.forEach((item => {
      //         if (item.id == this.categoryId) {
      //           ifAdd = false
      //           return
      //         }
      //       }))
      //       if (ifAdd) {
      //         this.categoryList.push(newCategory)
      //       }
      //       else {
      //         this.messageToastErr('Category has already exist!')
      //       }
      //       //添加完成后重置category数据
      //       this.form.firstCategory = ''
      //       this.form.secondaryCategory = ''
      //       this.secondaryData = []
      //       this.form.thirdCategory = ''
      //       this.thirdData = []
      //     }
      //   })
      // },
      //下面是对属性的操作。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
      //获取属性详情
      getPropertyDetail(id) {
        getPropertyDetail({id: id})
          .then(res => {
            if (res.data.errorID == 0) {
              this.form.name = this.$translateLang(res.data.object.name, 'unicodeTozawgyi') || ''
              this.form.nameMm = this.$translateLang(res.data.object.nameMm, 'unicodeTozawgyi') || ''
              this.form.status = res.data.object.status + ''
              this.categoryList = res.data.object.categories
              this.addForm.propertyId = res.data.object.id
            }
            else {
              this.messageToastErr(res.data.message)
            }
          })
      },
      //动态获取category
      // getNewCategory() {
      //   getCategory()
      //     .then(res => {
      //       let data = JSON.parse(res.data.object)
      //       this.categoryData = data
      //     })
      //     .catch(err => {
      //       console.log(err)
      //     })
      // },
      //删除
      // deleteItem(index) {
      //   this.$confirm('Are you sure to delete?', 'Notice', {
      //     confirmButtonText: 'Yes',
      //     cancelButtonText: 'No',
      //     type: 'warning'
      //   }).then(() => {
      //     this.categoryList.splice(index, 1)
      //     this.$message({
      //       type: 'success',
      //       message: 'Delete Success!'
      //     });
      //   }).catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: 'Delete Cancel'
      //     });
      //   });
      // },
      //提交对属性的编辑
      //下面是对属性值的操作。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
      //获取属性值列表
      getSubPropertyValue(pageNum) {
        this.tableLoading = true;
        if (pageNum == 1) {
          this.pageData.pageNum = 1;
        }
        getSubProperty(Object.assign({propertyId: this.id}, this.pageData))
          .then((res) => {
            this.tableData = res.data.object.list || []
            // 分页信息配置
            this.pageInfo.totalPages = res.data.object.pages
            this.pageInfo.totalCount = res.data.object.total
            this.tableLoading = false;
          })
          .catch((e) => {
            this.tableLoading = false;
          })
      },
      //增加新属性值
      // addPropertyValue() {
      //   let config = {
      //     "Content-Type": "multipart/form-data"
      //   };
      //   let params = {
      //     propertyId: this.addForm.propertyId,
      //     value: this.$translateLang(this.addForm.value || '', 'zawgyiTounicode') || '',
      //     valueMm: this.$translateLang(this.addForm.valueMm || '', 'zawgyiTounicode') || '',
      //   }
      //   params = Qs.stringify(params)
      //   propertyValueAdd(params, config)
      //     .then(res => {
      //       if (res.data.errorID == 0) {
      //         this.messageToastSuccess('Add success')
      //         this.getSubPropertyValue()
      //         this.addForm.value = ''
      //         this.addForm.valueMm = ''
      //       }
      //       else {
      //         this.$message({
      //           type: 'info',
      //           message: res.data.message
      //         });
      //       }
      //     })
      //     .catch(err => {
      //       console.log(err)
      //     })
      // },
      //删除属性值
      // deletePropertyValue(scope) {
      //   this.$confirm('Are you sure to delete?', 'Notice', {
      //     confirmButtonText: 'Yes',
      //     cancelButtonText: 'No',
      //     type: 'warning'
      //   }).then(() => {
      //     //调用属性值编辑接口，把status改成0
      //     let params = {
      //       value: scope.row.value,
      //       valueMm: scope.row.valueMm,
      //       status: 0,
      //       id: scope.row.id,
      //       propertyId: scope.row.propertyId
      //     }
      //     let config = {
      //       "Content-Type": "multipart/form-data"
      //     };
      //     params = Qs.stringify(params)
      //     propertyValueEdit(params, config)
      //       .then(res => {
      //         if (res.data.errorID == 0) {
      //           //弹出删除成功
      //           this.$message({
      //             type: 'success',
      //             message: 'Delete Success!'
      //           });
      //           //然后重新获取列表数据
      //           this.getSubPropertyValue()
      //         }
      //         else {
      //           this.$message({
      //             type: 'info',
      //             message: res.data.message
      //           });
      //         }
      //
      //       })
      //
      //   }).catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: 'Delete Cancel'
      //     });
      //   });
      // },
      //编辑属性值
      propertyValueEdit(scope, num) {
        let placeholder = ''
        let title = ''
        if (num === 1) {
          title = 'English'
          if (scope.row.value) {
            placeholder = scope.row.value
          }
          else {
            placeholder = 'Please Enter'
          }
        }
        else if (num === 2) {
          title = 'Mm'
          if (scope.row.valueMm) {
            placeholder = scope.row.valueMm
          }
          else {
            placeholder = 'Please Enter'
          }
        }
        this.$prompt(
          title,
          'Editing',
          {
            confirmButtonText: 'Save',
            cancelButtonText: 'Cancel',
            inputPlaceholder: placeholder,
            inputPattern: /\S/,
            inputErrorMessage: 'Can not be empty'
          }
        ).then(({value}) => {
          let newValue = this.$translateLang(value || '', 'zawgyiTounicode') || ''
          let params = {
            value: num === 1 ? newValue : scope.row.value,
            valueMm: num === 2 ? newValue : scope.row.valueMm,
            status: 1,
            id: scope.row.id,
            propertyId: scope.row.propertyId
          }
          let config = {
            "Content-Type": "multipart/form-data"
          };
          params = Qs.stringify(params)
          propertyValueEdit(params, config)
            .then(res => {
              if (res.data.errorID == 0) {
                //编辑成功 显示弹窗
                this.$message({
                  type: 'success',
                  message: 'Edit success'
                });
                //重新获取列表数据
                this.getSubPropertyValue()
              }
              else {
                this.$message({
                  type: 'info',
                  message: res.data.message
                });
              }

            })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: 'Edit cancel'
          });
        });
      },
      //提交对属性的编辑
      editProperty() {
        //对categoryList处理一下，只要id，不要name
        // let newArr = []
        // this.categoryList.forEach(item => {
        //   newArr.push(item.id)
        // })
        let params = {
          id: this.id,
          status: this.form.status,
          name: this.$translateLang(this.form.name || '', 'zawgyiTounicode') || '',
          nameMm: this.$translateLang(this.form.nameMm || '', 'zawgyiTounicode') || '',
          categoryIds: '',
        }
        params = Qs.stringify(params)
        updateProperty(params)
          .then(res => {
            if (res.data.errorID == 0) {
              this.messageToastSuccess('Update Success')
            }
            else {
              this.messageToastErr(res.data.message)
            }
          })
          .catch(err => {
            console.dir(err)
          })
      },
      // 下面是对表格的样式以及分页的操作。。。。。。。。。。。。。。。。。。。。。。。。。。
      // 用来控制表格行点击选中状态
      handleCurrentChange(val) {
        this.currentRow = val;
      },
      //用来控制单双行样式
      tableRowClassName({row, rowIndex}) {
        if (rowIndex % 2 === 1) {
          return 'odd-row';
        }
        else if (rowIndex % 2 === 0) {
          return 'even-row';
        }
        return '';
      },
      handleChangeSize(val) {
        this.pageData.pageSize = parseInt(val)
        this.pageData.pageNum = 1
        this.getSubPropertyValue()
      },
      handleChangePage(val) {
        this.pageData.pageNum = val
        this.getSubPropertyValue()
      },
      //对表格中的内容进行unicode转交集
      unicodeTozawgyi(value) {
        if (value) {
          return this.$translateLang(value, 'unicodeTozawgyi') || ''
        } else {
          return 'Click to translate';
        }
      },
      // message alert 用于前端错误提示信息
      messageToastErr(msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 5000,
          type: 'error'
        })
      },
      //成功消息提示
      messageToastSuccess(msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 5000,
          type: 'success'
        })
      },
    },
    mounted() {
      if (this.$route.query.id || this.$route.query.id == 0) {
        this.id = this.$route.query.id
        this.getPropertyDetail(this.id)
        this.getSubPropertyValue()
      }
      // this.getNewCategory()
    }
  }
</script>


<style>
  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px !important;
  }

  .breadcrumb {
    margin-bottom: 20px;
  }

  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px;
  }

  .search-box {
    position: relative;
    border-bottom: 1px solid #eee;
  }

  .container-padding {
    padding: 0 40px;
  }

  .card-wraper {
    position: relative;
    margin: 5px 0;
  }

  .card-wraper .delete-icon {
    position: absolute;
    right: 5px;
    top: 5px;
    font-size: 18px;
    color: red;
    cursor: pointer;
  }
</style>
